import {
	HTTP_REQUEST_URL,
	HEADER,
	TOKENNAME
} from '@/config/app';
import {
	toLogin,
	checkLogin
} from '../libs/login';
import store from "../store";
import formData from './formData';

const formdata = new formData();

function baseRequest(url, method, data, image, noAuth = false) {

	for (var key in data) {
		formdata.append(key, data[key]);
	}


	for (var key in image) {
		formdata.appendFile(key, image[key]);
	}

	let Url = HTTP_REQUEST_URL,
		newdata = formdata.getData();

	HEADER['content-type'] = newdata.contentType;
	let header = HEADER;
	/**
	 * 先用UID做鉴权 后面在用token
	 */
	if (!noAuth) {
		// 登录过期自动登录
		if (!store.state.app.uid) {
			// toLogin();
			// return Promise.reject('未登录');
		}
	}


	// if (!noAuth) {
	// 	//登录过期自动登录
	// 	if (!store.state.token && !checkLogin()) {
	// 		toLogin();
	// 		return Promise.reject({
	// 			msg: '未登录'
	// 		})
	// 	}
	// }
	// if (store.state.token) header[TOKENNAME] = store.state.token;

	return new Promise((resolve, reject) => {
		uni.request({
			url: Url + '/api/' + url,
			  //url: Url + '/' + url,
			method: method || 'GET',
			header: header,
			data: newdata.buffer || {},
			success: (res) => {
				if (res.data.resultCode == 1)
					resolve(res.data, res);
				else if ([410000, 410001, 410002].indexOf(res.data.resultCode) !== -1) {
					toLogin();
					reject(res.data);
				} else
					reject(res.data.message || '系统错误');
			},
			fail: (message) => {
				console.log(message);
				reject('请求失败');
			}
		})
	})
}



const request = {};

['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
	request[method] = (api, data, image, opt) => baseRequest(api, method, data, image, opt || false)
});

export default request;